import {messages} from "share/common";
/**
 * created by jsq on 2017/9/28
 */
import React from 'react'
import { connect } from 'react-redux'

import { Form, Input, Switch, Button, Icon, Row, Col, Alert, message, DatePicker, Select } from 'antd'
import budgetService from 'containers/budget-setting/budget-organization/budget-control-rules/budget-control-rulles.service'
import debounce from 'lodash.debounce';
import Inputter from 'components/inputter'
import chooserData from 'share/chooserData'


import "styles/budget-setting/budget-organization/budget-control-rules/new-budget-rules-detail.scss"
const FormItem = Form.Item;
const Option = Select.Option;

class NewBudgetRulesDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      ruleId: null,
      isEnabled: true,
      loading: false,
      ruleParameterTypeArray: [], //值列表：规则参数类型
      filtrateMethodArray: [],    //值列表：取值方式
      summaryOrDetailArray: [],   //值列表：取值范围
      ruleParamsArray: [],        //规则参数值列表
      paramValueMap: {},
      ruleParamDetail: {},
      validateStatusMap: {},
      helpMap: {},
      lov: {
        disabled: true
      },
      selectedData: {},
    };
  }

  componentWillMount() {
    let organizationIdParams = { organizationId: this.props.organization.id, isEnabled: true };
    let userSelectorItem = chooserData['user'];

    let itemSelectorItem = chooserData['budget_item'];
    let key = itemSelectorItem.searchForm[1].getUrl.split("?").length;
    if (key < 2) {
      itemSelectorItem.searchForm[1].getUrl += `?organizationId=${this.props.organization.id}&isEnabled=${true}`;
      itemSelectorItem.searchForm[2].getUrl += `?organizationId=${this.props.organization.id}&isEnabled=${true}`;
    }
    userSelectorItem.key = 'employeeID';
    let paramValueMap = {
      'BUDGET_ITEM_TYPE': {
        listType: 'budget_item_type',
        labelKey: 'id',
        valueKey: 'itemTypeName',
        codeKey: 'itemTypeCode',
        listExtraParams: organizationIdParams,
        selectorItem: undefined
      },

      'BUDGET_ITEM_GROUP': {
        listType: 'budget_item_group',
        labelKey: 'id',
        valueKey: 'itemGroupName',
        codeKey: 'itemGroupCode',
        listExtraParams: organizationIdParams,
        selectorItem: undefined
      },
      'BUDGET_ITEM': {
        listType: 'budget_item',
        labelKey: 'id',
        valueKey: 'itemName',
        codeKey: 'itemCode',
        listExtraParams: organizationIdParams,
        selectorItem: itemSelectorItem
      },
      'CURRENCY': {
        listType: 'currency',
        labelKey: 'currencyName',
        valueKey: 'currencyCode',
        codeKey: 'currencyCode',
        listExtraParams: {
          baseCurrencyCode: this.props.company.baseCurrency,
          language: 'zh_CN',
          enable: true,
          setOfBooksId: this.props.organization.setOfBooksId,
          tenantId: this.props.user.tenantId
        },
        selectorItem: undefined
      },
      'COMPANY': {
        listType: 'company',
        labelKey: 'id',
        valueKey: 'name',
        codeKey: 'companyCode',
        listExtraParams: { setOfBooksId: this.props.organization.setOfBooksId, enable: true },
        selectorItem: undefined
      },
      'COMPANY_GROUP': {
        listType: 'company_group',
        labelKey: 'id',
        valueKey: 'companyGroupName',
        codeKey: 'companyGroupCode',
        listExtraParams: { enabled: true, setOfBooksId: this.props.organization.setOfBooksId },
        selectorItem: undefined
      },
      'UNIT': {
        listType: 'department',
        labelKey: 'id',
        valueKey: 'custDeptNumber',
        codeKey: 'custDeptNumber',
        listExtraParams: { setOfBooksId: this.props.organization.setOfBooksId, enable: true },
        selectorItem: undefined
      },
      'UNIT_GROUP': {
        listType: 'department_group',
        labelKey: 'id',
        valueKey: 'name',
        codeKey: 'deptGroupCode',
        listExtraParams: { setOfBooksId: this.props.organization.setOfBooksId, enable: true },
        selectorItem: undefined
      },
      'EMPLOYEE': {
        listType: 'user',
        labelKey: 'fullName',
        valueKey: 'employeeID',
        codeKey: 'employeeID',
        listExtraParams: { roleType: 'TENANT', setOfBooksId: this.props.organization.setOfBooksId, enable: true, status: 1001 },
        selectorItem: userSelectorItem
      },
      'EMPLOYEE_GROUP': {
        listType: 'user_group',
        labelKey: 'name',
        valueKey: 'id',
        codeKey: 'code',
        listExtraParams: { setOfBooksId: this.props.organization.setOfBooksId, enabled: true },
        selectorItem: undefined
      },
      'BUDGET_SCENARIO': {
        listType: 'budget_scenarios',
        labelKey: 'scenarioName',
        valueKey: 'id',
        codeKey: 'scenarioCode',
        listExtraParams: organizationIdParams,
        selectorItem: undefined
      },
      'BUDGET_VERSION': {
        listType: 'budget_versions',
        labelKey: 'versionName',
        valueKey: 'id',
        codeKey: 'versionCode',
        listExtraParams: organizationIdParams,
        selectorItem: undefined
      },
      'BUDGET_STRUCTURE': {
        listType: 'budget_structure',
        labelKey: 'structureName',
        valueKey: 'id',
        codeKey: 'structureCode',
        listExtraParams: organizationIdParams,
        selectorItem: undefined
      },
      'YEAR': {
        listType: 'year',
        labelKey: 'year',
        codeKey: 'year',
        listExtraParams: { setOfBooksId: this.props.organization.setOfBooksId },
        selectorItem: undefined
      },
      'SEMIANNUAL':{
        listType: 'semiannual',
        labelKey: 'messageKey',
        valueKey: 'id',
        codeKey: 'code',
        listExtraParams: { type: 2031 },
        selectorItem: undefined
      },
      'QUARTER': {
        listType: 'quarter',
        labelKey: 'messageKey',
        valueKey: 'id',
        codeKey: 'code',
        listExtraParams: { type: 2021 },
        selectorItem: undefined
      },
      'MONTH': {
        listType: 'period',
        labelKey: 'periodName',
        valueKey: 'id',
        codeKey: 'periodName',
        listExtraParams: { setOfBooksId: this.props.organization.setOfBooksId },
        selectorItem: undefined
      },
    };
    this.getValueList(2014, this.state.summaryOrDetailArray);
    this.setState({
      ruleDetail: this.props.params,
      paramValueMap: paramValueMap
    });
  }
  /**
   * 获取值列表
   * @param code :值列表代码
   * @param name :值列表名称
  */
  getValueList = (code, name) => {
    name.splice(0, name.length);
    this.getSystemValueList(code).then(res => {
      res.data.values.map(item => {
        let option = {
          key: item.code,
          id: item.code,
          value: item.messageKey
        };
        name.addIfNotExist(option);
      });
      this.setState({ name })
    })
  };

  //获取成本中心及成本中心组类别
  getCostCenter(array) {
    let params = { setOfBooksId: this.props.organization.setOfBooksId, };
    budgetService.getCostCenterAndGroup(params).then((response) => {
      response.data.map((item) => {
        let option = {
          id: `${item.code}+${item.id}+${item.type}`,
          value: `${item.name}(${item.enabled ? messages('common.enabled') : messages('common.disabled')})`,
        };
        array.addIfNotExist(option);
        this.setState({
          array
        })
      });
    })
  }

  componentWillReceiveProps(nextprops) {
    this.setState({
      ruleId: nextprops.params,
      organizationId: this.props.organization.id
    })
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        let { validateStatusMap, helpMap } = this.state;
        Object.keys(err).map(key => {
          validateStatusMap[key] = "error";
          helpMap[key] = messages('common.please.select');
          this.setState({ validateStatusMap, helpMap })
        })
      }
      if (!err) {
        values.controlRuleId = this.props.ruleId;
        let str = values.ruleParameter.split("+");
        values.ruleParameter = str[0];
        values.ruleParameterId = str[1];
        values.ruleParameterSubType = str[2];
        this.setState({
          loading: true,
        });
        budgetService.addRuleDetail(values).then((res) => {
          this.setState({
            loading: false,
            filtrateMethodHelp: '',
            summaryOrDetailHelp: ''
          });
          if (res.status === 200) {
            this.props.close(true);
            message.success(`${messages('common.save.success', { name: "" })}`);
            let { validateStatusMap, helpMap } = this.state;
            validateStatusMap = {};
            helpMap = {};
            this.setState({
              loading: false,
              validateStatusMap,
              helpMap
            });
            this.props.form.resetFields();
          }
        }).catch((e) => {
          if (e.response) {
            message.error(`${messages('common.save.failed')}, ${e.response.data.message}`);
            this.setState({ loading: false });
          }
        })
      }
    });
  };

  onCancel = () => {
    this.props.form.resetFields();
    this.setState({
      ruleParameterTypeArray: [],
      ruleParamsArray: [],
      validateStatusMap: {},
      helpMap: {},
      loading: false,
      lov: {
        disabled: true
      }
    });
    this.detail = {};
    this.props.close();
  };

  //选择规则参数
  handleSelectParam = (value) => {
    let ruleParameterType = this.props.form.getFieldValue("ruleParameterType");
    //没有选择规则参数类型，提示：请先选择规则参数类型
    if (typeof ruleParameterType === 'undefined') {
      let { validateStatusMap, helpMap } = this.state;
      validateStatusMap.ruleParameter = "warning";
      helpMap.ruleParameter = messages('budget-setting.key41'/*请先选择规则参数类型*/);
      this.setState({
        validateStatusMap,
        helpMap
      })
    }
  };

  //修改规则参数类型
  handleRuleTypeChange = (value) => {
    if (!value) return;
    let { lov, ruleParamsArray } = this.state;
    lov.type = value;
    lov.disabled = true;
    this.setState({ lov });
    let ruleParameterCode;
    switch (value) {
      case 'BGT_RULE_PARAMETER_BUDGET': ruleParameterCode = 2015; break;
      case 'BGT_RULE_PARAMETER_ORG': ruleParameterCode = 2016; break;
      case 'BGT_RULE_PARAMETER_DIM': ruleParameterCode = 2017; break
    }
    if (ruleParameterCode === 2017) {
      ruleParamsArray.splice(0, ruleParamsArray.length);
      this.getCostCenter(ruleParamsArray)
    } else {
      this.getValueList(ruleParameterCode, ruleParamsArray)
    }
    //规则参数类型修改后，规则参数，上限值，下限值自动清空
    this.props.form.setFieldsValue({
      ruleParameter: undefined,
      parameterLowerLimit: undefined,
      parameterUpperLimit: undefined
    })
  };

  //修改规则参数
  handleRuleParamChange = (value) => {
    let { validateStatusMap, helpMap, lov, paramValueMap } = this.state;
    if (!value) {
      validateStatusMap.ruleParameter = "error";
      helpMap.ruleParameter = messages('common.please.select');
      this.setState({ validateStatusMap, helpMap })
    } else {
      let temp = {};
      if (lov.type === 'BGT_RULE_PARAMETER_DIM') {
        let ruleParamId = value.split('+')[1];
        let ruleParamType = value.split('+')[2];
        if (ruleParamType === 'CC') { //成本中心
          temp = {
            type: 'BGT_RULE_PARAMETER_DIM',
            listType: 'cost_center_item_by_id',
            listExtraParams: { costCenterId: ruleParamId },
            codeKey: 'code'
          }
        } else { //成本中心组类别 CCGC
          temp = {
            type: 'BGT_RULE_PARAMETER_DIM',
            listType: 'cost_center_group',
            listExtraParams: { costCenterGroupCategoryId: ruleParamId, enabled: true },
            codeKey: 'costCenterGroupCode'
          }
        }
      } else {
        temp = paramValueMap[value] || {}
      }
      temp.disabled = false;
      validateStatusMap.ruleParameter = "";
      helpMap.ruleParameter = "";
      this.setState({ lov: temp, validateStatusMap, helpMap });
      //规则参数修改后，上限值，下限值自动清空
      this.props.form.setFieldsValue({
        parameterLowerLimit: undefined,
        parameterUpperLimit: undefined
      });
    }
  };

  //修改取值方式
  handleRuleMethodChange = (value) => {
    let { validateStatusMap, helpMap } = this.state;
    if (!value) {
      validateStatusMap.ruleParameter = "error";
      helpMap.ruleParameter = messages('common.please.select');
      this.setState({ validateStatusMap, helpMap })
    } else {
      helpMap.filtrateMethod = (
        value === "INCLUDE" ? messages('budget-setting.key42'/*值范围为闭区间，包含左右边界值*/)
          : (value === "EXCLUDE" ? messages('budget-setting.key43'/*值范围为开区间，不包含左右边界值*/) : messages('common.please.select'))
      );
      validateStatusMap.filtrateMethod =  "";
      this.setState({ helpMap, validateStatusMap })
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;

    const { loading, lov, validateStatusMap, helpMap, ruleParameterTypeArray, filtrateMethodArray, summaryOrDetailArray,
      ruleParamsArray } = this.state;

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 },
    };

    return (
      <div className="new-budget-control-rules-detail">
        <Form onSubmit={this.handleSubmit}>
          <Row gutter={30}>
            <Col span={20}>
              <FormItem {...formItemLayout} label={messages('budget-setting.key24'/*规则参数类型*/)}>
                {getFieldDecorator('ruleParameterType', {
                  rules: [{
                    required: true,
                    message: messages('common.please.select')
                  }]
                })(
                  <Select
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                    className="input-disabled-color" placeholder={messages('common.please.select')}
                    onChange={this.handleRuleTypeChange}
                    onFocus={() => !ruleParameterTypeArray.length && this.getValueList(2012, ruleParameterTypeArray)}>
                    {
                      ruleParameterTypeArray.map((item) => <Option key={item.id}>{item.value}</Option>)
                    }
                  </Select>
                  )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={30}>
            <Col span={20}>
              <FormItem {...formItemLayout} label={messages('budget-setting.key25'/*规则参数*/)}
                validateStatus={validateStatusMap.ruleParameter}
                help={helpMap.ruleParameter}>
                {getFieldDecorator('ruleParameter', {
                  rules: [{
                    required: true,
                  }]
                })(
                  <Select
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                    onFocus={this.handleSelectParam}
                    onChange={this.handleRuleParamChange}
                    className="input-disabled-color" placeholder={messages('common.please.select')}>
                    {
                      ruleParamsArray.map((item) => <Option key={item.id}>{item.value}</Option>)
                    }
                  </Select>
                  )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={30}>
            <Col span={20}>
              <FormItem {...formItemLayout}
                label={messages('budget-setting.key26'/*取值方式*/)}
                validateStatus={validateStatusMap.filtrateMethod}
                help={helpMap.filtrateMethod}>
                {getFieldDecorator('filtrateMethod', {
                  rules: [{
                    required: true,
                    message: messages('common.please.select')
                  }],
                })(
                  <Select
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                    placeholder={messages('common.please.select')}
                    onFocus={() => !filtrateMethodArray.length && this.getValueList(2013, filtrateMethodArray)}
                    onChange={this.handleRuleMethodChange}
                    Control periodControl period>
                    {filtrateMethodArray.map((item) => <Option key={item.id}>{item.value}</Option>)}
                  </Select>
                  )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={30}>
            <Col span={20}>
              <FormItem {...formItemLayout} label={messages('budget-setting.key27'/*取值范围*/)}>
                {getFieldDecorator('summaryOrDetail', {
                  initialValue: "DETAIL",
                  rules: [{
                    required: true,
                    message: messages('common.please.select')
                  }]
                })(
                  <Select
                    disabled
                    placeholder={messages('common.please.select')}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                  >
                    {summaryOrDetailArray.map(item => <Option key={item.id}>{item.value}</Option>)}
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={30}>
            <Col span={20}>
              <FormItem {...formItemLayout} label={messages('budget-setting.key28'/*下限值*/)}>
                {getFieldDecorator('parameterLowerLimit', {
                  rules: [{
                    required: true,
                    message: messages('common.please.select')
                  }]
                })(
                  <Inputter type={lov.listType}
                            valueKey={lov.codeKey}
                            listExtraParams={lov.listExtraParams}
                            disabled={lov.disabled}
                  />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={30}>
            <Col span={20}>
              <FormItem {...formItemLayout} label={messages('budget-setting.key29'/*上限值*/)}>
                {getFieldDecorator('parameterUpperLimit', {
                  rules: [{
                    required: true,
                    message: messages('common.please.select')
                  }]
                })(
                  <Inputter type={lov.listType}
                            valueKey={lov.codeKey}
                            listExtraParams={lov.listExtraParams}
                            disabled={lov.disabled}/>
                  )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={30}>
            <Col span={20}>
              <FormItem {...formItemLayout} label={messages('budget-setting.key30'/*失效日期*/)}>
                {getFieldDecorator('invalidDate')(
                  <DatePicker placeholder={messages('common.please.enter')} />
                )}
              </FormItem>
            </Col>
          </Row>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')}</Button>
            <input ref="blur" style={{ position: 'absolute', top: '-9999vh' }} />
          </div>
        </Form>
      </div>
    )
  }
}
function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    user: state.login.user
  }
}

const WrappedNewBudgetRulesDetail = Form.create()(NewBudgetRulesDetail);
export default connect(mapStateToProps)(WrappedNewBudgetRulesDetail);
